package qianting.news.user.controller;

import cn.hutool.core.util.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import qianting.news.apis.models.user.pojos.ApUser;
import qianting.news.basic.filecenter.service.FileStorageService;
import qianting.news.common.constant.FilePrefixConstants;
import qianting.news.common.entity.State;
import qianting.news.user.service.ApUserService;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import java.io.ByteArrayInputStream;
import java.io.IOException;

@RestController
@RequestMapping("/")
public class ApUserController {

    @Autowired
    private ApUserService apUserService;

    @Autowired
    private FileStorageService fileStorageService;

    //修改用户名
    //TODO 修改完用户名后需要重置jwt
    @GetMapping("updateUsername/{id}/{username}")
    public State updateUsername(@PathVariable("id") Long id,@PathVariable("username") @NotBlank(message = "昵称不能为空") @Size(min = 3,max = 10,message = "用户名长度在3-10之间") String username){

        boolean b = apUserService.updateUsername(id, username);
        return State.succ(b);

    }

    //修改密码
    //TODO 修改完密码后需要重置jwt
    @GetMapping("updatePassword/{id}/{password}")
    public State updatePassword(@PathVariable("id") Long id,@PathVariable("password") @NotBlank(message = "密码不能为空") @Size(min = 4,max = 10,message = "密码长度在4-10之间") String password){

        boolean b = apUserService.updatePassword(id, password);
        return State.succ(b);

    }

    //修改用户的头像
    @PostMapping("editUserPortrait")
    public State editUserPortrait(Long id, MultipartFile file){

        String originalFilename = file.getOriginalFilename();
        String[] split = originalFilename.split("\\.");//这里如果不加\\表示匹配任意单个字符
        String type = split[1];
        //TODO 对图片的判断要读取魔数
        if(!type.equals("jpg")&&!type.equals("png")){
            return State.fail("图片类型不支持,仅支持jpg和png格式的图片");
        }
        byte[] bytes=new byte[1024];
        try {
            bytes=file.getBytes();
        }catch (IOException e){
            return State.fail("文件出现问题");
        }
        String filename = fileStorageService.uploadImgFile(FilePrefixConstants.USER_PORTRAIT_PREFIX, RandomUtil.randomString(20)+"."+type, new ByteArrayInputStream(bytes));
        //保存图片的名字
        boolean res = apUserService.editUserPortrait(id, filename);
        return State.succ(res);

    }

}
